package com.fate.system.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fate.framework.dto.IdParamDTO;
import com.fate.framework.utils.CommonUtil;
import com.fate.framework.utils.SystemUtil;
import com.fate.framework.vo.LabelValueVO;
import com.fate.system.dto.role.RoleAddDTO;
import com.fate.system.dto.role.RolePageDTO;
import com.fate.system.dto.role.RoleUpdateDTO;
import com.fate.system.entity.Role;
import com.fate.system.service.IRoleService;
import com.fate.system.vo.role.RoleDetailVO;
import com.fate.system.vo.role.RoleListVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.*;

@Tag(name = "角色操作 API")
@RestController
@RequestMapping("/api/v1.0/role")
public class RoleController {

  @Resource private IRoleService roleService;

  @SaCheckRole("super_admin")
  @Operation(summary = "新增")
  @PostMapping("/add")
  public void add(@RequestBody @Valid RoleAddDTO addDTO) {
    Role role = SystemUtil.buildResource(addDTO, Role.class);
    roleService.save(role);
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "删除")
  @PostMapping("/remove")
  public void remove(@RequestBody @Valid IdParamDTO idParamDTO) {
    roleService.removeRole(idParamDTO.getId());
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "更新")
  @PostMapping("/update")
  public void update(@RequestBody @Valid RoleUpdateDTO updateDTO) {
    Role role = SystemUtil.buildResource(updateDTO, Role.class);
    roleService.updateById(role);
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "详情")
  @PostMapping("/detail")
  public RoleDetailVO detail(@RequestBody @Valid IdParamDTO idParamDTO) {
    Role role = roleService.getById(idParamDTO.getId());
    return SystemUtil.buildResource(role, RoleDetailVO.class);
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "分页列表")
  @PostMapping("/getPageList")
  public Page<RoleListVO> getPageList(@RequestBody @Valid RolePageDTO pageDTO) {
    Page<Role> page = roleService.getPageList(pageDTO);
    return SystemUtil.buildResource(page, RoleListVO.class);
  }

  @SaCheckRole("super_admin")
  @Operation(summary = "下拉列表")
  @GetMapping("/getRoleSelects")
  public List<LabelValueVO> getRoleSelects() {
    List<Role> roleList = roleService.list();
    if (CommonUtil.isNullOrEmpty(roleList)) {
      return new ArrayList<>();
    }

    return roleList.stream()
        .map(role -> new LabelValueVO(role.getRoleName(), role.getId()))
        .toList();
  }
}
